/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.prod.wip.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.prod.procedure.dao.model.ProdWorkProcedure;
import com.erp.prod.procedure.dao.model.ProdWorkProcedureCO;
import com.erp.prod.procedure.dao.model.ProdWorkProcedureResource;
import com.erp.prod.procedure.dao.model.ProdWorkProcedureResourceCO;
import com.erp.prod.procedure.service.ProdWorkProcedureResourceService;
import com.erp.prod.procedure.service.ProdWorkProcedureService;
import com.erp.prod.resource.dao.model.ProdResource;
import com.erp.prod.resource.service.ProdResourceService;
import com.erp.prod.wip.dao.data.DataBox;
import com.erp.prod.wip.dao.model.ProdWipTaskProcedure;
import com.erp.prod.wip.dao.model.ProdWipTaskProcedureCO;
import com.erp.prod.wip.service.ProdWipTaskProcedureService;
import com.erp.prod.workcenter.dao.model.ProdWorkCenter;
import com.erp.prod.workcenter.dao.model.ProdWorkCenterCO;
import com.erp.prod.workcenter.service.ProdWorkCenterService;

@Controller
@RequestMapping("/web/prodWipTaskProcedure")
public class ProdWipTaskProcedureWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ProdWipTaskProcedureWebController.class);
    
    //服务层注入
    @Autowired
    private ProdWipTaskProcedureService prodWipTaskProcedureService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private ProdResourceService prodResourceService;
    @Autowired
    private ProdWorkCenterService prodWorkCenterService;
    @Autowired
    private ProdWorkProcedureService prodWorkProcedureService;
    @Autowired
    private ProdWorkProcedureResourceService prodWorkProcedureResourceService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getProdWipTaskProcedureList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-12-07 20:42:31
     * @author 
     * @param pages
     * @param prodWipTaskProcedureCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdWipTaskProcedureList")
    public String getProdWipTaskProcedureList(Pages pages, ProdWipTaskProcedureCO prodWipTaskProcedureCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //分页查询数据
        List<ProdWipTaskProcedure> prodWipTaskProcedureList = this.prodWipTaskProcedureService.getWipTaskProcedureListByTaskCode(pages, prodWipTaskProcedureCO);
        
        //获取工作中心列表
        ProdWorkCenterCO prodWorkCenterCO = new ProdWorkCenterCO();
        prodWorkCenterCO.setStatus("Y");
        prodWorkCenterCO.setApproveStatus("APPROVE");
        List<ProdWorkCenter> prodWorkCenterList = this.prodWorkCenterService.getDataObjects(prodWorkCenterCO);
        
        //循环任务工序
        for(ProdWipTaskProcedure prodWipTaskProcedure: prodWipTaskProcedureList) {
            //获取工作中心信息
            for(ProdWorkCenter prodWorkCenter: prodWorkCenterList) {
                if(prodWipTaskProcedure.getWorkCenterCode().equals(prodWorkCenter.getWorkCenterCode())) {
                    prodWipTaskProcedure.setWorkCenterName(prodWorkCenter.getWorkCenterName());
                    break;
                }
            }
            
            //获取工序信息
            ProdWorkProcedure prodWorkProcedure = this.prodWorkProcedureService.getDataObject(prodWipTaskProcedure.getProcedureCode());
            prodWipTaskProcedure.setProcedureName(prodWorkProcedure.getProcedureName());
        }
        
        //获取单位
        //Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //获取工序状态
        Map taskProcedureStatusMap = DataBox.getTaskProcedureStatusMap();
        
        //页面属性设置
        model.addAttribute("prodWipTaskProcedureList", prodWipTaskProcedureList);
        model.addAttribute("pages", pages);
        model.addAttribute("taskProcedureStatusMap", taskProcedureStatusMap);
        
        return "prodWipTask/tab/procedureLineTab";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-12-07 20:42:31
     * @author 
     * @param prodWipTaskProcedure
     * @param model
     * @return String
     *
     */
    @RequestMapping("getProdWipTaskProcedure")
    public String getProdWipTaskProcedure(ProdWipTaskProcedure prodWipTaskProcedure, Model model) {
        //获取工序
        ProdWorkProcedureCO prodWorkProcedureCO = new ProdWorkProcedureCO();
        prodWorkProcedureCO.setStatus("Y");
        prodWorkProcedureCO.setApproveStatus("APPROVE");
        List<ProdWorkProcedure> prodWorkProcedureList = this.prodWorkProcedureService.getDataObjects(prodWorkProcedureCO);
        
        //获取单据类型
        String procedureShiftType = prodWipTaskProcedure.getProcedureShiftType();
        
        //查询要编辑的数据
        if(prodWipTaskProcedure!=null&&prodWipTaskProcedure.getTaskProcedureId()!=null) {
            prodWipTaskProcedure = this.prodWipTaskProcedureService.getDataObject(prodWipTaskProcedure.getTaskProcedureId());
            
            //设置默认字段
            prodWipTaskProcedure.setProcedureShiftType(procedureShiftType);
            if(prodWipTaskProcedure.getProcedureShiftType().equals("SHIFT")) {
                prodWipTaskProcedure.setStatus("SHIFT");
            }else if(prodWipTaskProcedure.getProcedureShiftType().equals("FINISH")) {
                prodWipTaskProcedure.setStatus("SHIFT");
            }else if(prodWipTaskProcedure.getProcedureShiftType().equals("RETURN")) {
                prodWipTaskProcedure.setStatus("WORK");
            }
            
            //循环获取工序名称
            for(ProdWorkProcedure prodWorkProcedure: prodWorkProcedureList) {
                if(prodWorkProcedure.getProcedureCode().equals(prodWipTaskProcedure.getProcedureCode())) {
                    prodWipTaskProcedure.setProcedureName(prodWorkProcedure.getProcedureName());
                }
                if(prodWorkProcedure.getProcedureCode().equals(prodWipTaskProcedure.getShiftProcedureCode())) {
                    prodWipTaskProcedure.setShiftProcedureName(prodWorkProcedure.getProcedureName());
                }
            }
        }
        
//        //获取资源
//        ProdResourceCO prodResourceCO = new ProdResourceCO();
//        prodResourceCO.setStatus("Y");
//        prodResourceCO.setApproveStatus("APPROVE");
//        List<ProdResource> prodResourceList = this.prodResourceService.getDataObjects(prodResourceCO);
        

//        //获取工作中心列表
//        ProdWorkCenterCO prodWorkCenterCO = new ProdWorkCenterCO();
//        prodWorkCenterCO.setStatus("Y");
//        prodWorkCenterCO.setApproveStatus("APPROVE");
//        List<ProdWorkCenter> prodWorkCenterList = this.prodWorkCenterService.getDataObjects(prodWorkCenterCO);
        
        //获取单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        
        //获取工序转移单类型
        Map procedureShiftTypeMap = DataBox.getTaskProcedureShiftTypeMap();
        
        //获取工序状态
        Map taskProcedureStatusMap = DataBox.getTaskProcedureStatusMap();
        
        //页面属性设置
        model.addAttribute("prodWipTaskProcedure", prodWipTaskProcedure);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("procedureShiftTypeMap", procedureShiftTypeMap);
        model.addAttribute("taskProcedureStatusMap", taskProcedureStatusMap);
        
        return "prodWipTask/pop/addProcedureLineModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-12-07 20:42:31
     * @author 
     * @param prodWipTaskProcedure
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editProdWipTaskProcedure")
    @ResponseBody
    public String editProdWipTaskProcedure(@Valid ProdWipTaskProcedure prodWipTaskProcedure, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        try {
            //对当前编辑的对象初始化默认的字段
            if(prodWipTaskProcedure.getTaskProcedureId()==null) {
                prodWipTaskProcedure.setTaskProcedureCode(SnowFlake.getConcurrentId().toString());
            }
            
            //保存编辑的数据
            String message = this.prodWipTaskProcedureService.insertOrUpdateWipTaskProcedure(prodWipTaskProcedure);
            
            //判断是转移还是完工
            String refresh = "N";
            if(StringUtils.isBlank(prodWipTaskProcedure.getShiftProcedureCode())) {
                refresh = "Y";
            }
            
            return "{\"result\":\"success\", \"message\": \""+message+"\", \"refresh\": \""+refresh+"\"}";
        }catch(Exception e) {
            e.printStackTrace();
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-12-07 20:42:31
     * @author 
     * @param prodWipTaskProcedure
     * @return String
     *
     */
    @RequestMapping("deleteProdWipTaskProcedure")
    @ResponseBody
    public String deleteProdWipTaskProcedure(ProdWipTaskProcedure prodWipTaskProcedure, RedirectAttributes attr) {
        try {
            //删除数据前验证数据
            if(prodWipTaskProcedure!=null&&prodWipTaskProcedure.getTaskProcedureId()!=null) {
                //删除数据
                this.prodWipTaskProcedureService.deleteDataObject(prodWipTaskProcedure);
            }
            
            return "{\"result\":\"success\"}";
        }catch(Exception e) {
            return "{\"result\":\"error\"}";
        }
    }
    
    
    
    /**
     * 
     * @description 创建车间任务物料需求（异步）
     * @date 2020年12月21日
     * @author dongbin
     * @param taskCode
     * @return
     * @return String
     *
     */
    @RequestMapping("createWipTaskProcedureAjax")
    @ResponseBody
    public String createWipTaskProcedureAjax(String taskCode) {
        return this.prodWipTaskProcedureService.createWipTaskProcedure(taskCode);
    }
    
    
    
    /**
     * 
     * @description 获取工序资源成本（异步）
     * @date 2020年12月25日
     * @author dongbin
     * @param procedureCode
     * @param finishQuantity
     * @return String
     *
     */
    @RequestMapping("getProcedureResourceCostAjax")
    @ResponseBody
    public String getProcedureResourceCostAjax(String procedureCode, String finishQuantity) {
        BigDecimal costAmountSum = new BigDecimal(0D);
        //完成数量
        BigDecimal finishQuantityBigDecimal = new BigDecimal(Double.valueOf(finishQuantity));
        
        String countStr = "";
        try {
            //获取工序的资源
            Pages pages = new Pages();
            pages.setMax(100);
            pages.setPage(1);
            ProdWorkProcedureResourceCO prodWorkProcedureResourceCO = new ProdWorkProcedureResourceCO();
            prodWorkProcedureResourceCO.setProcedureCode(procedureCode);
            
            List<ProdWorkProcedureResource> prodWorkProcedureResourceList = this.prodWorkProcedureResourceService.getResourceListByWorkProcedureCode(pages, prodWorkProcedureResourceCO);
        
            //循环资源计算成本
            for(ProdWorkProcedureResource prodWorkProcedureResource: prodWorkProcedureResourceList) {
                ProdResource prodResource = this.prodResourceService.getDataObject(prodWorkProcedureResource.getResourceCode());
                //判定计费类型
                if(prodResource.getChargeType().equals("wip")&&prodResource.getCostFlag().equals("Y")) {
                    //基准类型(按数量或批量)
                    if(prodResource.getCountType().equals("materiel")) {
                        BigDecimal costAmount = new BigDecimal(prodWorkProcedureResource.getCostAmount());
                        BigDecimal quantity = new BigDecimal(prodWorkProcedureResource.getResourceQuantity());
                        //根据成本费率、资源数量、生产数量计算
                        BigDecimal resourceCost = costAmount.multiply(quantity).multiply(finishQuantityBigDecimal).setScale(2, BigDecimal.ROUND_HALF_UP);
                        countStr = countStr+"["+prodResource.getResourceName()+"]成本："+resourceCost.doubleValue()+"<br/>";
                        costAmountSum = costAmountSum.add(resourceCost);
                    }else if(prodResource.getCountType().equals("batch")) {
                        //直接计算成本
                        BigDecimal resourceCost = new BigDecimal(prodWorkProcedureResource.getCostAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        countStr = countStr+"["+prodResource.getResourceName()+"]成本："+resourceCost.toString()+"<br/>";
                        costAmountSum = costAmountSum.add(resourceCost);
                    }
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        
        return "{\"costAmount\": \""+costAmountSum.doubleValue()+"\", \"costHint\": \""+countStr+"\"}";
    }
}
